package research.model;

import java.util.List;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;

import research.entity.Entity;
import research.persistence.IPersistenceListener;
import research.persistence.IPersistenceManager;

public class EntityContentProvider implements IStructuredContentProvider,
		ITreeContentProvider, IPersistenceListener {
	private TreeViewer view;
	private IPersistenceManager datasource;
	private IHierarchyProvider hierarchy;
	
	public EntityContentProvider(IHierarchyProvider hierarchy) {
		super();
		this.hierarchy = hierarchy;
	}

	@Override
	public void inputChanged(Viewer view, Object oldInput, Object newInput) {
		this.view = (TreeViewer) view;
		this.datasource = (IPersistenceManager) newInput;
		IPersistenceManager oldManager = (IPersistenceManager) oldInput;
		IPersistenceManager newManager = (IPersistenceManager) newInput;
					
		if (oldManager != null)
			oldManager.removeListener(this);
		
		if (newManager != null)
			newManager.addListener(this);
	}
	
	@Override
	public void add(Entity entity) {
		if (hierarchy.supportsType(entity.getType())) {
			Object parent = getParent(entity);
			view.add(parent == null ? datasource : parent, entity);
		}
	}

	@Override
	public void remove(Entity entity) {
		if (hierarchy.supportsType(entity.getType()))
			view.remove(entity);
	}
	
	@Override
	public void update(Entity entity) {
		if (hierarchy.supportsType(entity.getType()))
			view.update(entity, null);
	}

	@Override
	public void dispose() {
	}

	@Override
	public Object[] getElements(Object parent) {
		List<Entity> res = datasource.getDataSource().getAll(hierarchy.getRootType());
		return res.toArray();
	}

	@Override
	public Object getParent(Object child) {
		if (child instanceof Entity) {
			Entity entity = (Entity) child;
			return datasource.getDataSource().getParent(entity, hierarchy);
		}
		return null;
	}

	@Override
	public Object[] getChildren(Object parent) {
		if (parent instanceof Entity) {
			Entity entity = (Entity) parent;
			return datasource.getDataSource().getChildren(entity, hierarchy).toArray();
		}
		return new Object[0];
	}

	@Override
	public boolean hasChildren(Object parent) {
		if (parent instanceof Entity) {
			Entity entity = (Entity) parent;
			return hierarchy.hasChildren(entity);
		}
		return false;
	}
}